package com.sname.car.record.service;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.sname.car.bike.entity.Point;
import com.sname.car.common.exception.CarException;
import com.sname.car.record.entity.RideContrail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author songx
 * @date 2018/9/26 17:13
 */
@Service
public class BikeGeoServiceImpl implements BikeGeoService {
    /**
     * Author song  醉美柳舞之众星捧月
     * Date & Time  2018/9/26 18:13
     * Description  MongoDB查询单车类！！！！
     */
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RideContrail rideContrail(String ride_contrail, String recordNo) throws CarException {
        try {
            /** 一定要熟知  这一条查询语句  !!!!!!!! **/
            DBObject obj = mongoTemplate.getCollection(ride_contrail).findOne(new BasicDBObject("record_no", recordNo));
            RideContrail rideContrail = new RideContrail();
            rideContrail.setRideRecordNo((String) obj.get("record_no"));
            rideContrail.setBikeNo(((Integer) obj.get("bike_no")).longValue());
            BasicDBList list = (BasicDBList) obj.get("contail");
            ArrayList<Point> pointList = new ArrayList<>();
            for (Object object : list) {
                BasicDBList loc = (BasicDBList) ((BasicDBObject) object).get("loc");
                Double[] doubles = new Double[2];
                loc.toArray(doubles);
                Point point = new Point(doubles);
                pointList.add(point);
            }
            rideContrail.setContrail(pointList);
            return rideContrail;
        } catch (Exception e
        ) {
            log.error("Fail to query ride contrail", e);
            throw new CarException("查询单车轨迹失败！");
        }
    }
}
